package com.dm0858.bianmin.mine.activity;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.mapapi.http.AsyncHttpClient;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.api.ApiService;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.databinding.ActivityEditPostLayoutBinding;
import com.dm0858.bianmin.mine.adapter.EditPostRecyclerViewAdapter;
import com.dm0858.bianmin.mine.base.BaseActivity;
import com.dm0858.bianmin.mine.bean.CarBeanData;
import com.dm0858.bianmin.mine.bean.HouseBeanData;
import com.dm0858.bianmin.mine.bean.NormalBeanData;
import com.dm0858.bianmin.mine.model.MineModel;
import com.dm0858.bianmin.mine.network.Retrofit;
import com.dm0858.bianmin.mine.network.RetrofitListener;
import com.dm0858.bianmin.mine.tools.GlideEngine;
import com.dm0858.bianmin.mine.tools.ItemDecorationUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.mine.viewmodel.MineViewModel;
import com.dm0858.bianmin.ui.activity.CacheUtils;
import com.dm0858.bianmin.ui.activity.IndustryAll;
import com.dm0858.bianmin.ui.activity.ReleaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author 迪迪丶Sir
 * @description 修改帖子
 * @e-mail asd969709719@qq.com
 * @since 2020-05-20
 **/
public class EditPostActivity extends BaseActivity implements View.OnClickListener {

    private ActivityEditPostLayoutBinding binding;

    private MineViewModel viewModel;

    private EditPostRecyclerViewAdapter adapter;

    private List<LocalMedia> images;

    private List<File> files = new ArrayList<>();

    private List<String> imageUrl = new ArrayList<>();

    private Retrofit retrofit;

    private int typeInt = 0;
    private String id = "";

    private NormalBeanData normal;
    private HouseBeanData house;
    private CarBeanData car;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        typeInt = getIntent().getIntExtra("typeInt",0);
        id = getIntent().getStringExtra("id");
        initView();

    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this,R.layout.activity_edit_post_layout);
        binding.setOnClick(this);
        if (retrofit == null) retrofit = new Retrofit();
        switch (typeInt) {
            case 0:
                binding.body.txt1.setText("标题");
                binding.body.txt2.setText("身份信息");
                binding.body.txt3.setText("备案证明");
                binding.body.txt4.setText("地址");
                binding.body.txt5.setText("详细地址");
                binding.body.txt6.setText("联系人");
                binding.body.txt7.setText("联系电话");
                binding.body.txt11.setText("内容");
                gone(binding.body.txt8);
                gone(binding.body.edt8);
                gone(binding.body.txt9);
                gone(binding.body.edt9);
                gone(binding.body.txt10);
                gone(binding.body.edt10);
                break;
            case 10:
                binding.body.txt1.setText("标题");
                binding.body.txt2.setText("地区");
                binding.body.txt3.setText("详细地址");
                binding.body.txt4.setText("小区名称");
                binding.body.txt5.setText("户型");
                binding.body.txt6.setText("面积");
                binding.body.txt7.setText("价格");
                binding.body.txt8.setText("联系人");
                binding.body.txt9.setText("联系电话");
                binding.body.txt11.setText("房源描述");
                gone(binding.body.txt10);
                gone(binding.body.edt10);
                break;
        }
        initData();
    }

    private void gone(View view) {
        view.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(MineViewModel.class);
        viewModel.editPost(typeInt,id);
        viewModel.getNormal().observe(this, dataBean -> {
            if (dataBean == null) return;
            this.normal = dataBean;
            binding.body.edt1.setText(dataBean.getTitle());
            binding.body.edt2.setText("");
            binding.body.edt3.setText(dataBean.getBeian());
            binding.body.edt4.setText(dataBean.getArea());
            binding.body.edt5.setText(dataBean.getAddr());
            binding.body.edt6.setText("");
            binding.body.edt7.setText(dataBean.getTel());
            binding.body.edtContent.setText("");
        });
        viewModel.getHouse().observe(this, dataBean -> {
            if (dataBean == null) return;
            this.house = dataBean;
            binding.body.edt1.setText(dataBean.getTitle());
            binding.body.edt2.setText(dataBean.getArea());
            binding.body.edt3.setText(dataBean.getAddr());
            binding.body.edt4.setText(dataBean.getXiaoqu());
            binding.body.edt5.setText(dataBean.getHuxing());
            binding.body.edt6.setText(dataBean.getMianji());
            binding.body.edt7.setText(dataBean.getJiage());
            binding.body.edt8.setText("");
            binding.body.edt9.setText(dataBean.getTel());
            binding.body.edtContent.setText("");
        });
        viewModel.getCar().observe(this, dataBean -> {
            if (dataBean == null) return;
            this.car = dataBean;
            binding.body.edt1.setText(dataBean.getTitle());
            binding.body.edt2.setText(dataBean.getChengxing());
            binding.body.edt3.setText(dataBean.getLicheng());
            binding.body.edt4.setText(dataBean.getShangpai());
            binding.body.edt5.setText(dataBean.getPailiang());
            binding.body.edt6.setText(dataBean.getJiage());
            binding.body.edt7.setText(dataBean.getAddr());
            binding.body.edt8.setText(dataBean.getAddr());
            binding.body.edt9.setText("");
            binding.body.edt10.setText(dataBean.getTel());
            binding.body.edtContent.setText("");
        });


        setRecyclerView();
    }

    private void setRecyclerView() {
        if (adapter == null) adapter = new EditPostRecyclerViewAdapter(this,R.layout.adapter_edit_post_picture_item_layout,null);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(this,3){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        binding.recyclerview.addItemDecoration(new ItemDecorationUtils(4,4,4,4,0));
        binding.recyclerview.setAdapter(adapter);
        adapter.setOnItemClick(position -> {
            images.remove(position);
            adapter.setImages(images);
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofAll())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(List<LocalMedia> result) {
                                images = result;
                                // 结果回调
                                adapter.setImages(images);
                                for (LocalMedia image : result) {
                                    Uri uri = Uri.parse(image.getPath());
                                    File file = getBitmapFormUri(EditPostActivity.this,uri);
                                    files.add(file);
                                }
                            }
                            @Override
                            public void onCancel() {
                                // 取消
                            }
                        });
                break;

            case R.id.btn_commit:
                myHandler.sendEmptyMessage(1);
                break;
        }
    }

    /**
     * 通过uri获取图片并进行压缩
     *
     * @param uri
     * @return
     */
    public static File getBitmapFormUri(Activity ac, Uri uri) {
        Bitmap bitmap = null;
        try {
            InputStream input = ac.getContentResolver().openInputStream(uri);
            BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
            onlyBoundsOptions.inJustDecodeBounds = true;
            onlyBoundsOptions.inDither = true;//optional
            onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
            BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
            input.close();
            int originalWidth = onlyBoundsOptions.outWidth;
            int originalHeight = onlyBoundsOptions.outHeight;
            if ((originalWidth == -1) || (originalHeight == -1))
                return null;
            //图片分辨率以480x800为标准
            float hh = 800f;//这里设置高度为800f
            float ww = 480f;//这里设置宽度为480f
            //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
            int be = 1;//be=1表示不缩放
            if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
                be = (int) (originalWidth / ww);
            } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
                be = (int) (originalHeight / hh);
            }
            if (be <= 0)
                be = 1;
            //比例压缩
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmapOptions.inSampleSize = be;//设置缩放比例
            bitmapOptions.inDither = true;//optional
            bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
            input = ac.getContentResolver().openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return compressImage(bitmap);//再进行质量压缩
    }


    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        //图片名
        String filename = format.format(date);

        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    private int i = 0;

    private MyHandler myHandler = new MyHandler();
    AjaxParams params = new AjaxParams();
    class MyHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (i < files.size()){
                        upload(files.get(i));
                        i++;
                    }else {
                        myHandler.sendEmptyMessage(typeInt);
                    }
                    break;
                //正常的
                case 0:
                    params.put("classid", normal.getSectionId());
                    params.put("title", binding.body.edt1.getText().toString());
                    params.put("call", binding.body.edt7.getText().toString());
                    params.put("username", binding.body.edt6.getText().toString());
                    params.put("address", binding.body.edt4.getText().toString() + binding.body.edt5.getText().toString());
                    params.put("content", binding.body.edtContent.getText().toString());
                    params.put("zuobiao", normal.getLat() + "," + normal.getLng());
                    params.put("city", normal.getCity());
                    params.put("state", "1");
                    params.put("shengfen", binding.body.edt2.getText().toString());
                    params.put("beian", binding.body.edt3.getText().toString());
                    params.put("msgpic", normal.getImage());
                    submitMsg();
                    break;
                //租房买房
                case 10:
                    //房屋
                    params.put("classid", house.getSectionId());
                    params.put("title", binding.body.edt1.getText().toString());
                    params.put("call", binding.body.edt9.getText().toString());
                    params.put("username", binding.body.edt8.getText().toString());
                    params.put("address", binding.body.edt2.getText().toString() + binding.body.edt3.getText().toString());
                    params.put("content", binding.body.edtContent.getText().toString());
                    params.put("zuobiao", house.getLat() + "," + house.getLng());
                    params.put("city", house.getCity());
                    params.put("state", "1");
                    params.put("xiaoqu", binding.body.edt4.getText().toString());
                    params.put("huxing", binding.body.edt5.getText().toString());
                    params.put("mianji", binding.body.edt6.getText().toString());
                    params.put("jiage", binding.body.edt7.getText().toString());
                    params.put("msgpic", house.getImage());
                    submitMsg();
                    break;
                //二手汽车
                case 17:
                    //汽车
                    params.put("classid", car.getSectionId());
                    params.put("title", binding.body.edt1.getText().toString());
                    params.put("call", binding.body.edt10.getText().toString());
                    params.put("username", binding.body.edt9.getText().toString());
                    params.put("address", binding.body.edt7.getText().toString() + binding.body.edt8.getText().toString());
                    params.put("zuobiao", car.getLat() + "," + car.getLng());
                    params.put("city", car.getCity());
                    params.put("state", "1");
                    params.put("chengxing", binding.body.edt2.getText().toString());
                    params.put("licheng", binding.body.edt3.getText().toString());
                    params.put("shangpai", binding.body.edt4.getText().toString());
                    params.put("pailiang", binding.body.edt5.getText().toString());
                    params.put("content", binding.body.edtContent.getText().toString());
                    params.put("jiage", binding.body.edt6.getText().toString());
                    params.put("msgpic", car.getImage());
                    submitMsg();
                    break;
            }

        }
    }

    private void submitMsg() {
        params.put("userid", MyApp.userid);
        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/info.php?func=saveArticle", params, new AjaxCallBack(){


            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Toast.makeText(EditPostActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                onBackPressed();


            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Toast.makeText(EditPostActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");
            }
        });
    }


    /*
     * 作用：上传图片，并携带参数
     * 传入参数：http_url（服务器目标地址），filepath（本机图片的地址）
     */
    public void upload(final File file){
        AjaxParams params = new AjaxParams();
        try {
            params.put("file", file);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(EditPostActivity.this, "上传失败",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        FinalHttp fh = new FinalHttp();
        fh.post("http://bmshfw.net/phpapi/bmahoutai/uploadone.php", params, new AjaxCallBack(){
            @Override
            public void onLoading(long count, long current) {

                Log.v("dddddd","正在上传");

            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                Log.v("dddddd","上传成功");
                myHandler.sendEmptyMessage(1);

            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Toast.makeText(EditPostActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
                Log.v("dabadbd","上传NO");

            }
        });
    }

    /***
     *  把StringJson转换为list类型
     */
    public <IndustryAll> List<com.dm0858.bianmin.ui.activity.IndustryAll> getIndustryAlls() {
        List<com.dm0858.bianmin.ui.activity.IndustryAll> datalist=new ArrayList<com.dm0858.bianmin.ui.activity.IndustryAll>();
        String  industryAllStr = CacheUtils.getIndustry(this);

        if (null == industryAllStr) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(industryAllStr, new TypeToken<List<com.dm0858.bianmin.ui.activity.IndustryAll>>() {
        }.getType());
        return datalist;

    }

























}